<?php

namespace App\Livewire;

use App\Enums\BorrowStatus;
use App\Models\Book;
use App\Models\BorrowRecord;
use App\Settings\Borrow;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class BorrowList extends Component
{
    public  $tabs;
    public  $status = 'all';
    public function mount()
    {
        $this->tabs = BorrowStatus::getFilterValue();
    }
    public function render()
    {
        return view('livewire.borrow-list',[
            'books' => $this->getPageData(),
        ]);
    }

    public function renewalBorrowRecord(BorrowRecord $record,Borrow $borrowSetting)
    {
        if (!$record->renewal && $record->returned == BorrowStatus::STATUS_BORROWING){
            $record->renewal = true;
            $record->deadline = $record->deadline->addDays($borrowSetting->borrow_extend);
            $record->save();
            $this->dispatch('success', '续借成功');
         }
        $this->dispatch('error','续借失败');
    }

    public function getPageData(): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query = BorrowRecord::query()
            ->where('member_id',auth('frontend')->id());
        if ($this->status != 'all'){
            $query->where('returned',$this->status);
        }
        return $query->orderByDesc('created_at')
            ->paginate(10);
    }
}
